package manager;

import java.io.*;
import java.util.*;

import common.*;
import bean.*;

import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.RootClass;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Iterator;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.RootClass;
import org.hibernate.tool.hbm2ddl.SchemaExport;

/**
 * Servlet implementation class manager
 */
@WebServlet("/manager")
public class manager extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Session session;
	Transaction tx; 

    /**
     * @see HttpServlet#HttpServlet()
     */
    public manager() {
        super();
        // TODO Auto-generated constructor stub
        session = HibernateUtil.getCurrentSession();
		tx = session.beginTransaction();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String parameter;
		
		if ((parameter = request.getParameter("init")) != null) {
			System.out.println("__INIT");
			makeSelectCtrl(request, response);
		}
		else if ((parameter = request.getParameter("sel")) != null) {
			System.out.println("__SEL");
			makeTable(request, response, parameter);
		}
		else if ((parameter = request.getParameter("locale")) != null) {
			System.out.println("__LOCALE");
			makeLocale(request, response);
		}
		else if ((parameter = request.getParameter("lsel")) != null) {
			System.out.println("__LSEL");
			makeLocaleTable(request, response, parameter);
		}
		else if ((parameter = request.getParameter("zipCity")) != null) {
			System.out.println("__ZIPCITY");
			makeZipCity(request, response);
		}
		else if ((parameter = request.getParameter("CitySel")) != null) {
			System.out.println("__ZIPCITY");
			makeZipCodeTable(request, response, parameter);
		} else {
			System.out.println("__WRONG!!!");
			//makeTable(request, response, parameter);
		//requestProcess(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
	
	public void makeSelectCtrl(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		setTableName("day", "day150104");
		
		String query = "from day group by city";
		String outString = "";
		
		response.setContentType("text/xml;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		List<day> day = (List<day>)session.createQuery(query).list();
		if (day != null) {
			outString = makeJsonCity(day);
			System.out.println(outString);
			out.println(outString);
			out.close();
		}
	}
	
	public String makeJsonCity(List<day> l){
		
		String strJsonCity = "{\"city\":[";
		
		for (int i = 0; i < l.size(); i++)
		{
			day c = (day)l.get(i);
			
			strJsonCity += "{\"num\" : \"" + c.getNum() + "\", \"city\" : \"" + c.getCity() + "\"}";
			
			strJsonCity = attachJsonTail(strJsonCity, i, l.size());
		}
		
		return strJsonCity;
	}

	public void makeTable(HttpServletRequest request, HttpServletResponse response, String parameter) throws ServletException, IOException {
		setTableName("day", "day150104");
		
		String query = "from day where num=" + parameter;
		String outString = "";
		
		System.out.println(query);
		
		response.setContentType("text/xml;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		List<day> day = (List<day>)session.createQuery(query).list();
		if (day != null) {
			outString = makeJsonDay(day);
			System.out.println(outString);
			out.println(outString);
			out.close();
		}
	}
	
	public String makeJsonDay(List<day> l){
		String strJsonDay = "{\"day\":[";
		
		for (int i = 0; i < l.size(); i++)
		{
			day c = (day)l.get(i);
			
			strJsonDay += "{\"time\" : \"" + c.getTime() 
			     + "\", \"sunshine\" : \"" + c.getSunshine()
				+ "\", \"isolation\" : \"" + c.getIsolation()
				+ "\", \"temperature\" : \"" + c.getTemperature()
				+ "\"}";
			
			strJsonDay = attachJsonTail(strJsonDay, i, l.size());
		}
		
		return strJsonDay;
	}

	public void makeLocale(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String query = "from locale";
		String outString = "";
		
		response.setContentType("text/xml;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		List<locale> locale = (List<locale>)session.createQuery(query).list();
		
		outString = makeJsonLocale(locale);
		System.out.println(outString);
		out.println(outString);
		out.close();
	}
	
	public String makeJsonLocale(List<locale> l){	
		String strJsonlocale = "{\"locale\":[";
		
		for (int i = 0; i < l.size(); i++)
		{
			locale c = (locale)l.get(i);
			
			strJsonlocale += "{\"id\" : \"" + c.getId() + "\", \"locale\" : \"" + c.getLocale() + "\"}";
			
			strJsonlocale = attachJsonTail(strJsonlocale, i, l.size());
		}
		
		return strJsonlocale;
	}
	public void makeLocaleTable(HttpServletRequest request, HttpServletResponse response, String parameter) throws ServletException, IOException {
		String query = "from solarinfo s where s.locale=" + parameter;
		String outString = "";
		System.out.println(query);
		response.setContentType("text/xml;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		List<solarinfo> solarinfo = (List<solarinfo>)session.createQuery(query).list();
		
		outString = makeJsonLocaleTable(solarinfo);
		System.out.println(outString);
		out.println(outString);
		out.close();
	}
	
	public String makeJsonLocaleTable(List<solarinfo> l){
		String strJsonSolarinfo = "{\"solarinfo\":[";
		
		for (int i = 0; i < l.size(); i++)
		{
			solarinfo c = (solarinfo)l.get(i);
			
			strJsonSolarinfo += "{\"month\" : \"" + c.getMonth() 
			     + "\", \"airTemp\" : \"" + c.getAirTemp()
				+ "\", \"relativeHum\" : \"" + c.getRelativeHum()
				+ "\", \"dailySolar\" : \"" + c.getDailySolarRadiation()
				+ "\", \"atmoPres\" : \"" + c.getAtmoPres()
				+ "\", \"windSpeed\" : \"" + c.getWindSpeed()
				+ "\", \"landTemp\" : \"" + c.getLandTemp()
				+ "\"}";
			
			strJsonSolarinfo = attachJsonTail(strJsonSolarinfo, i, l.size());
		}
		
		return strJsonSolarinfo;
	}

	public void makeZipCity(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String query = "from city";
		String outString = "";
		
		response.setContentType("text/xml;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		List<city> city = (List<city>)session.createQuery(query).list();
		
		outString = makeJsonZipCity(city);
		System.out.println(outString);
		out.println(outString);
		out.close();
	}
	
	public String makeJsonZipCity(List<city> l){	
		String strJsoncity= "{\"city\":[";
		
		for (int i = 0; i < l.size(); i++)
		{
			city c = (city)l.get(i);
			strJsoncity += "{\"tablecode\" : \"" + c.getTableCode() + "\", \"city\" : \"" + c.getCity() + "\"}";
			
			strJsoncity = attachJsonTail(strJsoncity, i, l.size());
		}
		
		return strJsoncity;
	}
	
	public void makeZipCodeTable(HttpServletRequest request, HttpServletResponse response, String parameter) throws ServletException, IOException {
		setTableName("zipcode", parameter); 
				
		String query = "from zipcode group by state";// + parameter;
		String outString = "";
		System.out.println(query);
		response.setContentType("text/xml;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		List<zipcode> zipcode = (List<zipcode>)session.createQuery(query).list();
		System.out.println(zipcode.size());
		outString = makeGetZipCode(zipcode);
		System.out.println(outString);
		out.println(outString);
		out.close();
	}
	
	public String makeGetZipCode(List<zipcode> l){	
		String strJsonZipCode= "{\"zipcode\":[";
		
		for (int i = 0; i < l.size(); i++)
		{
			zipcode c = (zipcode)l.get(i);
			strJsonZipCode += "{\"id\" : \"" + c.getId() + 
					  "\", \"zipcode\" : \"" + c.getZipcode() +
			          "\", \"city\" : \"" + c.getCity() +
			          "\", \"state\" : \"" + c.getState() +
			          "\"}";
			
			strJsonZipCode = attachJsonTail(strJsonZipCode, i, l.size());
		}
		
		return strJsonZipCode;
	}
	
	public void setTableName(String strBefore, String strAfter) {
		if (tx != null)
			tx.rollback();
		
		HibernateUtil.setTableName(strBefore, strAfter);
		
		session = HibernateUtil.getCurrentSession();
		tx = session.beginTransaction();
	}
	
	public String attachJsonTail(String strJson, int i, int size) {
		if (i+1 != size) {
			strJson += ",";
		} else {
			strJson += "]}";
		}
		return strJson;
	}
}